package whitelist

import (
	"encoding/json"
	"errors"
	"fmt"
	"thais/database/redis"
	"thais/utils"
	"time"

	"github.com/bugfan/to"
)

const vpnKeyTemplate = "http_maps|%s"
const expireTime = 60 * 60 * 1e9

type PostHostMap struct {
	Key  string
	User string
	Maps map[string]HostMap
}

type HostMap struct {
	Target           string            `json:"target"`
	Scheme           string            `json:"scheme"`
	Tunnel           string            `json:"tunnel"`
	RealIP           string            `json:"real_ip"`
	ClientCertficate string            `json:"client_certficate"`
	Replace          map[string]string `json:"replace"`
}

func NewRedisMapper(post *PostHostMap) (string, error) {
	bs, err := json.Marshal(post)
	if err != nil {
		return "", err
	}
	if post.Key == "" {
		post.Key = utils.RandStringRunes(64)
	}
	redisKey := fmt.Sprintf(vpnKeyTemplate, post.Key)
	if !redis.WhiteList.Set(redisKey, to.String(bs), time.Duration(expireTime)) {
		return "", errors.New("Redis save fail")
	}
	return post.Key, nil
}

func GetAllRedisMapper() (interface{}, error) {

	allKey, err := redis.WhiteList.Keys("*")
	if err != nil {
		return nil, err
	}

	res := make(map[string]map[string]HostMap)

	for _, m := range allKey {
		var key string
		fmt.Sscanf(m, vpnKeyTemplate, &key)
		r, err := getMapFromRedis(m)
		if err != nil {
			return nil, err
		}
		res[key] = r.Maps
	}

	return res, nil
}
func getMapFromRedis(m string) (res *PostHostMap, err error) {
	str := redis.WhiteList.Get(m)
	redis.WhiteList.Expire(m, expireTime)
	err = json.Unmarshal([]byte(str), &res)
	if err != nil {
		return nil, err
	}
	return
}

func GetList(key string) ([]string, error) {
	return []string{"*"}, nil
}
